//
//  BanBu_BubbleViewController.m
//  BanBu
//
//  Created by Wang Xj on 13-7-20.
//
//

#import "BanBu_BubbleViewController.h"
#import "AppDataManager.h"
#import "BanBu_ThemeManager.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
#import "BanBuAPIs.h"
#import "BanBu_BubbleCell.h"

@interface BanBu_BubbleViewController ()

@end

@implementation BanBu_BubbleViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self)
    {
        
    }
    return self;
}

-(void)popself
{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)btn_refresh:(UIButton *)sender
{    
    NSInteger count = self.bubbleArray.count;//默认图片的数量
    [self setDefaultBubble:count];
    
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"];
    
    [FileManager removeItemAtPath:fileName error:nil];
    [ThemeManager getMore:BanBu_GetMoreBubbleImage];
}

-(void)setDefaultBubble:(NSInteger)bubbleCount
{
    [self.bubbleArray removeAllObjects];
    for (int i = 0; i<bubbleCount; i++)
    {
        UIImage * image = [UIImage imageNamed:@"bubbleDefault.png"];
        
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:i],KeyBubbleID,image,@"image", nil];
        
        [self.bubbleArray addObject:dic];
        
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    BanBu_NavButton *btn_refresh = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    btn_refresh.position = ButtonPositionRight;
    btn_refresh.frame=CGRectMake(0, 0,40, 30);
    [btn_refresh addTarget:self action:@selector(btn_refresh:) forControlEvents:UIControlEventTouchUpInside];
    [btn_refresh setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];
    btn_refresh.titleLabel.font = [UIFont systemFontOfSize:14];
    UIBarButtonItem *cancelItem = [[[UIBarButtonItem alloc] initWithCustomView:btn_refresh] autorelease];
    self.navigationItem.rightBarButtonItem = cancelItem;
    [btn_refresh release];
    
    
    ThemeManager.bubbleView = self;
    UIImage * selectedImage = [UIImage imageNamed:@"ResultIconSuccess@2x.png"];
    self.selectedImageView = [[[UIImageView alloc]init] autorelease];
    self.selectedImageView.image = selectedImage;
    
    self.title = NSLocalizedString(@"colorfulBubble", nil);
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc]initWithBackGroundImageType:UIImageViewCreatTypeTable]autorelease];
    if(img.image)
    {
        self.tableView.backgroundView = img;
    }
    

    self.bubbleArray = [NSMutableArray arrayWithCapacity:14];
    
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"];
    
    if (![[NSFileManager defaultManager ] fileExistsAtPath:fileName])
    {
        [[NSFileManager defaultManager]createDirectoryAtPath:fileName withIntermediateDirectories:YES attributes:nil error:nil];//创建气泡文件夹
    }
    
    self.bubbleInfoPath = [fileName stringByAppendingPathComponent:@"bubbleInfo.plist"];
    [self getDefault];
    [self checkNum];
    
    NSString * bubbleDirPath;
    
    NSDictionary * bubbleNameDic = [NSDictionary dictionaryWithContentsOfFile:self.bubbleInfoPath];
    
    if (bubbleNameDic.count)
    {
        for (int i = 0 ; i < bubbleNameDic.count; i++)
        {
            NSString * bubbleName =[NSString stringWithFormat:@"bubble_%d",i];
            
            bubbleDirPath = [fileName stringByAppendingPathComponent:bubbleName];
            
            bubbleDirPath = [bubbleDirPath stringByAppendingPathComponent:@"aio_user_bg_nor@2x.png"];
            
            UIImage * image = [UIImage imageWithContentsOfFile:bubbleDirPath];
            if (!image)
            {
                continue;
            }
            
            [MyAppDataManager.bubbleNameDic setValue:bubbleName forKey:[NSString stringWithFormat:@"%d",i]];
            NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:i],KeyBubbleID,image,@"image", nil];
            
            [self.bubbleArray addObject:dic];
        }
    }
    else //设有气泡时，显示默认图片
    {
        //上一界面获取气泡数量，这里铺上默认图片
    }
    //初始化table头
    [self initTableViewHeader];

    //直接加载
    [self getMore];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    if (self.bubbleArray.count!=0)
    {
        [self setSelected];
    }
    [self.tableView addSubview:self.selectedImageView];
    
    self.download = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    MyAppDataManager.selectedBubbleIndex = [[UserDefaults valueForKey:@"selectedBubbleIndex"] integerValue];
    self.download = YES;
    ThemeManager.bubbleView = nil;
    self.navigationController.view.userInteractionEnabled = YES;
    [self dismissModalView];
}

//初始化table头
-(void)initTableViewHeader
{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 290, 100)];
    backView.backgroundColor = [UIColor clearColor];
    
    UITextView * headerText = [[UITextView alloc]initWithFrame:CGRectMake(15, 25, 290, 50)];
    headerText.backgroundColor = [UIColor whiteColor];
    headerText.font = [UIFont boldSystemFontOfSize:15];
    headerText.textColor = [UIColor darkGrayColor];
    headerText.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    headerText.layer.borderWidth = .8;
    headerText.userInteractionEnabled = NO;
    headerText.editable = NO;
    headerText.layer.cornerRadius = 8.0;
    headerText.textAlignment = kTextAlignmentCenter;
    
    headerText.text = NSLocalizedString(@"helpfulTitle", nil);
    
    headerText.text =[headerText.text stringByAppendingFormat:@"\n%@",NSLocalizedString(@"chooseWhitchYouLike", nil)];
    
    [backView addSubview:headerText];
    self.tableView.tableHeaderView = backView;
    [headerText release];
    [backView release];
}

-(void)checkNum
{
    NSString * bubbleFolderPath = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"]stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"];
    
    NSMutableDictionary * bubbleNameDic = [NSMutableDictionary dictionaryWithContentsOfFile:self.bubbleInfoPath];
    
    NSArray * contentsArray = [FileManager contentsOfDirectoryAtPath:bubbleFolderPath error:nil];
    
    if (contentsArray.count - 2 > bubbleNameDic.count)//说明info.plist中有没有写入的bubble
    {
        for (NSString * bubbleName in contentsArray)
        {
            if (![bubbleNameDic valueForKey:bubbleName])
            {
                if ([bubbleName rangeOfString:@"plist"].location == NSNotFound)
                {
                    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1],bubbleName,[NSNumber numberWithInt:1],@"id", nil];
                    [bubbleNameDic setValue:dic forKey:bubbleName];
                }
            }
        }
    }
    
    [bubbleNameDic writeToFile:self.bubbleInfoPath atomically:YES];
    
}

#pragma mark - 默认聊天气泡，在这里可以修改 yinlinlin
-(void)getDefault
{
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"];
    
    self.bubbleInfoPath = [fileName stringByAppendingPathComponent:@"bubbleInfo.plist"];
    
    NSString * bubble_0 = [fileName stringByAppendingPathComponent:@"bubble_0"];
    
    //2014年10月10日15:31:30 by yinlinlin 检测是否保存bubble_0，加一次就可以了，下次不隐藏
//    if ([[NSFileManager defaultManager]fileExistsAtPath:bubble_0])
//    {
//        return;
//    }
    
    if ([[NSFileManager defaultManager]fileExistsAtPath:bubble_0])
    {
        [[NSFileManager defaultManager] removeItemAtPath:bubble_0 error:nil];
    }
    [[NSFileManager defaultManager]createDirectoryAtPath:bubble_0 withIntermediateDirectories:YES attributes:nil error:nil];
    
    NSString * fileString = [[NSBundle mainBundle]pathForResource:@"chat_voice_bubble-lef@2x" ofType:@"png"];
    
    NSString * toPath =[bubble_0 stringByAppendingPathComponent:@"aio_friend_bg_nor@2x.png"];
    
    [[NSFileManager defaultManager]copyItemAtPath:fileString toPath:toPath error:nil];
    fileString = [[NSBundle mainBundle]pathForResource:@"chat_voice_bubble-right@2x" ofType:@"png"];
    toPath = [bubble_0 stringByAppendingPathComponent:@"aio_user_bg_nor@2x.png"];
    [[NSFileManager defaultManager]copyItemAtPath:fileString toPath:toPath error:nil];
    
    NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1],@"bubble_0", @"0",@"id",nil ];
    NSMutableDictionary * dictionary = [NSMutableDictionary dictionaryWithCapacity:1];
    if ([[NSFileManager defaultManager]fileExistsAtPath:self.bubbleInfoPath])
    {
        dictionary = [NSMutableDictionary dictionaryWithContentsOfFile:self.bubbleInfoPath];
    }
    [dictionary setValue:dic forKey:@"bubble_0"];
    [dictionary writeToFile:self.bubbleInfoPath atomically:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return ceilf(self.bubbleArray.count/2.0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    BanBu_BubbleCell *cell = (BanBu_BubbleCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if(!cell)
    {
        cell = [[[BanBu_BubbleCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.delegate = self;
    }

    NSDictionary * bubbleInfo = [self.bubbleArray objectAtIndex:indexPath.row*2];
    
    cell.imageView1.image = (UIImage *)[bubbleInfo valueForKey:@"image"];
    cell.bubbleID1 = [bubbleInfo valueForKey:KeyBubbleID];
   
    if (indexPath.row == 0)
    {
        cell.imageView1.frame = CGRectMake(15, 5, 102, 90);
    }
    else
    {
        cell.imageView1.frame = CGRectMake(15, 5, 130, 90);
    }
    
    if (self.bubbleArray.count>=(indexPath.row*2+2))
    {
        bubbleInfo = [self.bubbleArray objectAtIndex:indexPath.row*2+1];
        
        cell.imageView2.image = (UIImage *)[bubbleInfo valueForKey:@"image"];
        cell.bubbleID2 = [bubbleInfo valueForKey:KeyBubbleID];
        
        cell.imageView2.userInteractionEnabled = YES;
    }
    else
    {
        cell.imageView2.userInteractionEnabled = NO;
        cell.imageView2.image = nil;
        cell.bubbleID2 = nil;
    }

    return cell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

#pragma mark - BubbleShowDelegate

-(void)menuShow:(UIView *)sender tableCell:(BanBu_BubbleCell *)sendert
{
    NSInteger index = sender.tag;
    if (index == 1)
    {
        MyAppDataManager.selectedBubbleIndex = [sendert.bubbleID1 integerValue];
    }
    else
    {
        MyAppDataManager.selectedBubbleIndex = [sendert.bubbleID2 integerValue];
    }
    
    [self setSelectedWithCell:sendert andIndex:index];
    
    self.navigationController.view.userInteractionEnabled = NO;
    
    UIAlertView * alert = [[[UIAlertView alloc]initWithTitle:NSLocalizedString(@"conform", nil) message:NSLocalizedString(@"bubbleAlertTitle", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"reChoose", nil) otherButtonTitles:NSLocalizedString(@"returnConform", nil), nil] autorelease];
    
    [alert performSelector:@selector(show) withObject:nil afterDelay:0.25];
}

#pragma mark -

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0:
        {
            MyAppDataManager.selectedBubbleIndex = [[UserDefaults valueForKey:@"selectedBubbleIndex"] integerValue];
            [self setSelected];
        }
            break;
        case 1:
        {
            [UserDefaults setValue:[NSNumber numberWithInteger:MyAppDataManager.selectedBubbleIndex] forKey:@"selectedBubbleIndex"];
            CGRect frame = self.selectedImageView.frame;
            
            NSDictionary * frameDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:frame.origin.x],@"frameX",[NSNumber numberWithFloat:frame.origin.y],@"frameY", nil] ;
            [UserDefaults setValue:frameDic forKey:@"selectedBubbleFrame"];
            [UserDefaults synchronize];
            
            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
        default:
            break;
    }
    
    self.navigationController.view.userInteractionEnabled = YES;
}

-(void)setSelectedWithCell:(BanBu_BubbleCell *)cell andIndex:(NSInteger)index
{
    CGRect rect = [self.tableView rectForRowAtIndexPath:[self.tableView indexPathForCell:cell]];
    
    NSInteger tag = index-1;
    
    [self.selectedImageView setFrame:CGRectMake((tag)*160+39, rect.origin.y+19, 72, 72)];
}

-(void)setSelected
{
    CGFloat x = [[[UserDefaults valueForKey:@"selectedBubbleFrame"] valueForKey:@"frameX"] floatValue];
    CGFloat y = [[[UserDefaults valueForKey:@"selectedBubbleFrame"] valueForKey:@"frameY"] floatValue];
    
    if (x<10 && y<10)
    {
        //第一次进界面，默认选中第一个图片
        x = 39;
        y = 114;
        
        NSDictionary * frameDic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:x],@"frameX",[NSNumber numberWithFloat:y],@"frameY", nil] ;
        [UserDefaults setValue:frameDic forKey:@"selectedBubbleFrame"];
        [UserDefaults synchronize];
    }
    CGRect frame = CGRectMake(x, y, 72, 72);
    
    self.selectedImageView.frame = frame;
}
-(void)getMore
{
    [ThemeManager getMore:BanBu_GetMoreBubbleImage];
    
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"chuliNotice", nil) activityAnimated:YES];
}

-(void)dismissModalView
{
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0];
}

//刷新界面
-(void)refreshView
{
    NSString * fileName = [[[NSHomeDirectory() stringByAppendingPathComponent:@"Library"] stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:@"BubbleImageFolder"];
    
    NSString * bubbleDirPath;
    
    NSDictionary * bubbleNameDic = [NSDictionary dictionaryWithContentsOfFile:self.bubbleInfoPath];
    
    for (int i =0 ; i < bubbleNameDic.count; i++)
    {
        NSString * bubbleName =[NSString stringWithFormat:@"bubble_%d",i];
        
        bubbleDirPath = [fileName stringByAppendingPathComponent:bubbleName];
        
        bubbleDirPath = [bubbleDirPath stringByAppendingPathComponent:@"aio_user_bg_nor@2x.png"];
        
        UIImage * image = [UIImage imageWithContentsOfFile:bubbleDirPath];
        if (!image || self.bubbleArray.count <= i)
        {
            continue;
        }
        
        [MyAppDataManager.bubbleNameDic setValue:bubbleName forKey:[NSString stringWithFormat:@"%d",i]];
        
        NSDictionary * dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:i],KeyBubbleID,image,@"image", nil];
        [self.bubbleArray replaceObjectAtIndex:i withObject:dic];
    }
    
    [self.tableView reloadData];
}


-(void)dealloc
{
    [_selectedImageView release],_selectedImageView = nil;
    [_bubbleInfoPath release],_bubbleInfoPath = nil;
    [_bubbleArray release],_bubbleArray = nil;
    
    [super dealloc];
}
@end












